package com.hboxs.asl.controller.asl.member;

import com.hboxs.asl.Filter;
import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.Principal;
import com.hboxs.asl.controller.asl.BaseController;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.service.MemberRankService;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.util.WebUtils;
import com.hboxs.asl.util.sms.ChuangLanSms;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by hboxs on 22/6/15.
 */
@Controller("phoneController")
@RequestMapping("/phone")
public class PhoneContorller extends BaseController {

	/** 验证码 */
	public static final String VALIDATE_PHONE_CODE = "VALIDATE_PHONE_CODE";
	/** 验证手机号码 */
	public static final String VALIDATE_PHONE = "VALIDATE_PHONE";
	/** 发送时间 */
	public static final String SEND_CODE_TIME = "SEND_CODE_TIME";
	private static final String content = "亲爱的用户，您的验证码是%s，5分钟内有效。";// 短信内容
	private static final String validatecontent = "您的找回密码验证码是%s，5分钟内有效。";// 短信内容
	/** 间隔5分钟*/
	private static final Long availableTime = 5 * 60 * 1000l;
	protected Logger logger = Logger.getLogger(getClass().getName());
	@Resource(name = "memberServiceImpl")
	private MemberService memberService;
	@Resource(name = "memberRankServiceImpl")
	private MemberRankService memberRankService;

	@RequestMapping(value = "/sendCode", method = RequestMethod.GET)
	@ResponseBody
	protected Object sendCode(String phone, HttpServletRequest request) throws HttpException, IOException {
		try {
			HttpSession session = request.getSession();

			Long lastSentTime = (Long) session.getAttribute(SEND_CODE_TIME);
			if (lastSentTime != null) {
				Long nowTime = new Date().getTime();
				if ((nowTime - lastSentTime) < availableTime) {
					return JsonMessage.error("验证码已经发送，请稍后重试");
				}
			}

			StringBuilder code = new StringBuilder();

//			if (memberService.phoneExists(phone)) {
//				return JsonMessage.errorMessage("对不起，该手机已注册");
//			}

			if (memberService.usernameExists(phone)) {
				return JsonMessage.error("对不起，该手机已注册");
			}

			Random random = new Random();
			// 6位验证码
			for (int i = 0; i < 6; i++) {
				code.append(String.valueOf(random.nextInt(10)));
			}

			session.setAttribute(VALIDATE_PHONE, phone);
			session.setAttribute(VALIDATE_PHONE_CODE, code.toString());
			Long sissionTime=new Date().getTime();
			session.setAttribute(SEND_CODE_TIME, sissionTime);

			if(phone.equals("15622330741")){
//				System.out.println("code:"+code);
				return JsonMessage.success("验证码发送成功");
			}
			
			String smsText = String.format(content, code);
			// System.out.println("手机号：" + phone + ", " + smsText);
			// SendMsg_webchinese.sendMessage(phone, smsText);
			try {
				Map<String, Object> retMap = new HashMap<>();
				// 创蓝
				 Map<String, Object> map = ChuangLanSms.sendSms(phone, smsText);
				 logger.error("短信发送结果:" + map.get(ChuangLanSms.KEY_MESSAGE));
				 retMap.put("ret", map.get(ChuangLanSms.KEY_MESSAGE));


				retMap.put("sissionTime", sissionTime);
				return JsonMessage.success(retMap);
			} catch (Exception e) {
				e.printStackTrace();
			}

			return JsonMessage.error("发送短信错误");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping("/validateCode")
	@ResponseBody
	protected Object validateCode(String phone, HttpServletRequest request) throws HttpException, IOException {
		try {
			HttpSession session = request.getSession();
			
			Long lastSentTime = (Long) session.getAttribute(SEND_CODE_TIME);
			if (lastSentTime != null) {
				Long nowTime = new Date().getTime();
				if ((nowTime - lastSentTime) < availableTime) {

					return JsonMessage.error("验证码已经发送，请稍后重试");
				}
			}
			if(!memberService.phoneExists(phone)){

				return JsonMessage.error("手机号码不存在!");
			}
			
			StringBuilder code = new StringBuilder();
			Random random = new Random();
			// 6位验证码
			for (int i = 0; i < 6; i++) {
				code.append(String.valueOf(random.nextInt(10)));
			}

			session.setAttribute(VALIDATE_PHONE, phone);
			session.setAttribute(VALIDATE_PHONE_CODE, code.toString());
			Long sissionTime=new Date().getTime();
			session.setAttribute(SEND_CODE_TIME, sissionTime);
			
			String smsText = String.format(validatecontent, code);
			// System.out.println("手机号：" + phone + ", " + smsText);
			// SendMsg_webchinese.sendMessage(phone, smsText);
			try {
				Map<String, Object> retMap = new HashMap<>();
				// 创蓝
				 Map<String, Object> map = ChuangLanSms.sendSms(phone, smsText);
				 logger.error("短信发送结果:" + map.get(ChuangLanSms.KEY_MESSAGE));
				 retMap.put("ret", map.get(ChuangLanSms.KEY_MESSAGE));
//				// 谐和科技
//				Map<String, Object> map = XieHeKeJiSms.batchSend(smsText, phone);
//				logger.info("短信发送结果:" + map.get(XieHeKeJiSms.KEY_MESSAGE));
//				retMap.put("ret", map.get(XieHeKeJiSms.KEY_MESSAGE));

				retMap.put("sissionTime", sissionTime);

				return JsonMessage.success(retMap);
			} catch (Exception e) {
				e.printStackTrace();
			}

			return JsonMessage.error("发送短信错误");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	@RequestMapping("/validate")
	@ResponseBody
	protected String validate(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		String code = (String) session.getAttribute(VALIDATE_PHONE_CODE);
		String phone = (String) session.getAttribute(VALIDATE_PHONE);
		String inputCode = request.getParameter("code");
		String inputPhone = request.getParameter("phone");
		if (phone.equals(inputPhone) && code.equalsIgnoreCase(inputCode)) {
			List<Filter> filters = new ArrayList<>();
			filters.add(Filter.eq("phone", phone));
			List<Member> members = memberService.findList(1, filters, null);
			Member m;
			if (members != null && members.size() > 0) {
				m = members.get(0);
			} else {
				Member member = new Member();
				member.setPhone(phone);
				member.setUsername(phone);
				member.setPassword(DigestUtils.md5Hex("0"));
				member.setEmail("@");
				member.setPoint(new BigDecimal(0));
				member.setAmount(new BigDecimal(0));
				member.setBalance(new BigDecimal(0));
				member.setIsEnabled(true);
				member.setIsLocked(false);
				member.setLoginFailureCount(0);
				member.setLockedDate(null);
				member.setRegisterIp(request.getRemoteAddr());
				member.setLoginIp(request.getRemoteAddr());
				member.setLoginDate(new Date());
				member.setSafeKey(null);
				member.setMemberRank(memberRankService.findDefault());
				member.setFavoriteProducts(null);
				memberService.save(member);
				m = member;
			}
			session.invalidate();
			session = request.getSession();
			session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(m.getId(), phone));
			WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, m.getUsername());
			return "success";
		} else {
			return "failure";
		}
	}
}
